package com.ruoyi.project.wx.controller;


import com.ruoyi.common.utils.bootdo.PageUtils;
import com.ruoyi.common.utils.bootdo.Query;
import com.ruoyi.common.utils.bootdo.R;
import com.ruoyi.project.wx.api.ApiWeChatPayController;
import com.ruoyi.project.wx.domain.OrderOrderDO;
import com.ruoyi.project.wx.domain.OrderShippingDO;
import com.ruoyi.project.wx.domain.ShopExpressCodeDO;
import com.ruoyi.project.wx.service.OrderOrderService;
import com.ruoyi.project.wx.service.OrderShippingService;
import com.ruoyi.project.wx.service.SetWechatService;
import com.ruoyi.project.wx.service.ShopExpressCodeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单信息表
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2019-05-27 17:57:00
 */
 
@Controller
@RequestMapping("/wx/orderOrder")
public class OrderOrderController {
	@Autowired
	private OrderOrderService orderOrderService;
	@Autowired
	private ShopExpressCodeService shopExpressCodeService;
	@Autowired
	private OrderShippingService orderShippingService;
	@Autowired
	private SetWechatService setWechatService;
	
	@GetMapping()
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String OrderOrder(){
	    return "wx/orderOrder/orderOrder";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.getOrderList(query);
		int total = orderOrderService.getOrderListCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wx:orderOrder:add")
	String add(){
	    return "wx/orderOrder/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wx:orderOrder:edit")
	String edit(@PathVariable("id") String id,Model model){
		OrderOrderDO orderOrder = orderOrderService.get(id);
		model.addAttribute("orderOrder", orderOrder);
	    return "wx/orderOrder/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wx:orderOrder:add")
	public R save(OrderOrderDO orderOrder){
		if(orderOrderService.save(orderOrder)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wx:orderOrder:edit")
	public R update( OrderOrderDO orderOrder){
		orderOrderService.update(orderOrder);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wx:orderOrder:remove")
	public R remove( String id){
		if(orderOrderService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wx:orderOrder:batchRemove")
	public R remove(@RequestParam("ids[]") String[] ids){
		orderOrderService.batchRemove(ids);
		return R.ok();
	}

	/*
	* 去发货
	* */
	@GetMapping("/shipments/{id}")
	@RequiresPermissions("wx:orderOrder:edit")
	String shipments(@PathVariable("id") String id,Model model){
		OrderOrderDO orderOrder = orderOrderService.get(id);
		model.addAttribute("orderOrder", orderOrder);
		List<ShopExpressCodeDO> list = shopExpressCodeService.list(new HashMap<>());
		model.addAttribute("codeList", list);
		return "wx/orderOrder/shipments";
	}

	/**
	 * 确认、修改发货
	 */
	@ResponseBody
	@PostMapping("/setShipments")
	@RequiresPermissions("wx:orderOrder:edit")
	public R setShipments( OrderOrderDO orderOrder){
		int status = orderOrder.getStatus();
		if (status != 3 && status != 4) {
			return R.error("订单状态错误");
		}
		//添加物流
		if (status == 3) {
			if(orderOrderService.addShipping(orderOrder)>0){
				return R.ok();
			}
		}
		//修改物流
		if (status == 4) {
			if(orderOrderService.editShipping(orderOrder)>0){
				return R.ok();
			}
		}
		return R.error();
	}

	/*修改收货地址*/
	@GetMapping("/editShipping/{id}")
	@RequiresPermissions("wx:orderShipping:edit")
	String editShipping(@PathVariable("id") String id,Model model){
		OrderShippingDO orderShippingDO = orderShippingService.getByOrderId(id);
		model.addAttribute("orderShipping", orderShippingDO);
		return "wx/orderShipping/edit";
	}

	/*
	* 订单详情
	* */
	@GetMapping("/orderInfo/{id}")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String orderInfo(@PathVariable("id") String id,Model model){
		Map<String,Object> map = orderOrderService.getHOrderById(id);
		model.addAttribute("order", map);
		return "wx/orderOrder/orderInfo";
	}

	/*去统计页面*/
	@GetMapping("/statistics")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String statistics(@RequestParam Map<String, Object> params,Model model){
		model.addAttribute("map", params);
		return "wx/orderOrder/statisticsList";
	}

	/**
	 * 统计查询
	 */
	@ResponseBody
	@RequestMapping("/statisticsList")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	public PageUtils statisticsList(@RequestParam Map<String, Object> params){
		String status = params.get("status").toString();
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.statisticsList(query);
		int total = orderOrderService.statisticsCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}

	/*去订单商品详情页面*/
	@GetMapping("/detailGoods/{id}")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String detailGoods(@PathVariable("id") String id,Model model){
		model.addAttribute("id",id);
		return "wx/orderOrder/detailGoods";
	}

	/**
	 * 获取订单商品详情
	 */
	@ResponseBody
	@RequestMapping("/getDetailGoods")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	public PageUtils getDetailGoods(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.getDetailGoods(query);
		int total = orderOrderService.getDetailGoodsCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}

	/*去砍价人员页面*/
	@GetMapping("/kUsers/{id}")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String kUsers(@PathVariable("id") String id,Model model){
		model.addAttribute("id",id);
		return "wx/orderOrder/kUsers";
	}

	/**
	 * 获取砍价人员详情
	 */
	@ResponseBody
	@RequestMapping("/getkUsers")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	public PageUtils getkUsers(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.getKUsers(query);
		int total = orderOrderService.getKUsersCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}

	/**
	 * 导出代发货excel表格
	 */
	@RequestMapping( "/exportExcel")
	@RequiresPermissions("wx:orderOrder:excel_out")
	public void exportExcel(@RequestParam("orderSn") String orderSn,@RequestParam("eTime") String eTime,
							@RequestParam("sTime") String sTime,@RequestParam("exports") String export,
							HttpServletResponse response,HttpServletRequest request){
		try
		{
			//1.查找代发货订单列表
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("orderSn",orderSn);
			map.put("eTime",eTime);
			map.put("sTime", sTime);
			map.put("export", export);
			map.put("status","3");
			List<Map<String,Object>> orderList = orderOrderService.getOrderList(map);
			for (Map<String,Object> orderMap : orderList) {
				List<Map<String,Object>> goodsList = orderOrderService.getDetailGoods(orderMap);
				orderMap.put("goodsList",goodsList);
			}
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("待发货订单列表.xls".getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			orderOrderService.exportExcel(map,orderList, outputStream,request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 导入代发货excel表格
	 */
	@ResponseBody
	@RequestMapping( "/importExcel")
	@RequiresPermissions("wx:orderOrder:excel_in")
	public R importExcel(@RequestParam("file")MultipartFile multipartFile, HttpServletResponse response){
		/*try {
			FileUtil.multipartFileToFile(multipartFile);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		if(multipartFile!= null) {
			String userExcelFileName = multipartFile.getOriginalFilename();
			//判断是否是Excel文件
			if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$"))
			{
				orderOrderService.importExcel(multipartFile, userExcelFileName);
			}
		}
		int a = 0;
		return R.ok();
	}

	@GetMapping("/back")
	@RequiresPermissions("wx:orderOrder:back")
	String back(){
		return "wx/orderOrder/backOrder";
	}

	/*
	* 退货订单列表
	* */
	@ResponseBody
	@GetMapping("/backList")
	@RequiresPermissions("wx:orderOrder:back")
	public PageUtils backList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.getBackOrderList(query);
		int total = orderOrderService.getBackOrderListCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}

	/**
	 * 后台退货订单操作
	 */
	@PostMapping( "/backOrder")
	@ResponseBody
	@RequiresPermissions("wx:orderOrder:backOrder")
	public R backOrder(OrderOrderDO order) throws Exception {
		if (order.getStatus() == 6) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("orderId",order.getId());
			ApiWeChatPayController apiWeChatPayController = new ApiWeChatPayController();
			try {
				return apiWeChatPayController.refund(order.getId(),orderOrderService,setWechatService);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (orderOrderService.backOrder(order) > 0) {
			return R.ok();
		}
		return R.error();
	}


}
